﻿using RMS.BLL;
using RMS.Common;
using RMS.EF.Model;
using RMS.Manage.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMS.Manage.Web.Areas.Demo.Controllers
{
    public class TablesController : BaseController
    {

        /// <summary>
        /// 表格
        /// </summary>
        /// <returns></returns>
        public ActionResult Tables()
        {
            return View();
        }
        #region DataTables
        /// <summary>
        /// 从数据库获取数据的表格
        /// </summary>
        /// <returns></returns>
        public ActionResult DataTables()
        {
            return View();
        }
        /// <summary>
        /// datatables获取数据
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="enable">是否可用</param>
        /// <param name="sort">排序字段</param>
        /// <param name="sortOrder">排序顺序</param>
        /// <returns></returns>
        public ActionResult DataTablesGetData(string userName, int? enable, string sort, string sortOrder)
        {
            ConnectTestBll bll = new ConnectTestBll();
            PageParams page = SetPageParams();
            var data = bll.GetByPage(page, userName, (E_Status)enable);
            var result = SetPageJson(page, data);
            return Json(result);
        }
        /// <summary>
        /// 编辑页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DataTables_Edit(string id)
        {
            Demo_User model = new Demo_User();
            ConnectTestBll bll = new ConnectTestBll();
            if (!string.IsNullOrWhiteSpace(id))
            {
                //var m = bll.GetById(id);
                //model = EntityHelper.ConverToTEntity<Demo_User_Extend>(m);
                model = bll.GetById(id);
                model.RePassword = model.Password;
            }

            var enabledItems = new List<SelectListItem>
            {
                new SelectListItem {Text = "--- 请选择 ---", Value = "-1", Selected = true},
                new SelectListItem {Text = "可用", Value = "1"},
                new SelectListItem {Text = "不可用", Value = "0"}
            };
            ViewBag.EnableItems = enabledItems;
            return PartialView(model);
        }
        [HttpPost]
        public ActionResult DataTables_Edit(Demo_User model)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            try
            {
                var dic = model.Validate();
                if (dic!=null)
                {
                    result.ErrorDic = dic;
                    return Json(result);
                }
                ConnectTestBll bll = new ConnectTestBll();
                //Demo_User userVm = EntityHelper.ConverToTEntity<Demo_User>(model);
                Demo_User userVm = model;
                if (!string.IsNullOrWhiteSpace(userVm.Id))
                {
                    result = bll.SaveEditUserInfo(userVm);
                }
                else
                {
                    userVm.Id = Guid.NewGuid().ToString();
                    result = bll.SaveAddUserInfo(userVm);
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return Json(result);

        }
        /// <summary>
        /// 删除和批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DataTables_Delete(string id)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    throw new Exception("请先选择要删除的数据！");
                }
                ConnectTestBll bll = new ConnectTestBll();
                result = bll.Delete(id);
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return Json(result);
        }
        /// <summary>
        /// 上传并导入excel数据表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult DataTables_Upload()
        {
            var IsSuccess = false;
            var Message = string.Empty;
            var FileUpladAudio = "/Upload/Demo/Upload/";
            var file = Request.Files["Filedata"];
            IsSuccess = FileHelper.SaveAutoName(file, FileUpladAudio, out Message);
            if (IsSuccess == false)
            {
                if (Message == "NoFile")
                {
                    Message = "请上传图片";
                }
                return Json(new { IsSuccess = IsSuccess, Message = Message }, "text/json", JsonRequestBehavior.AllowGet);
            }
            //支持.xls和.xlsx，即包括office2010等版本的   HDR=Yes代表第一行是标题，不是数据；
            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

            System.Data.DataTable dt = new System.Data.DataTable();
            //建立连接
            string serverPath = Server.MapPath("~");
            var fileUrl = serverPath + Message;
            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
            bool f = true;
            string msg = "";
            try
            {
                OleDbDataAdapter da = new OleDbDataAdapter("select * from [sheet1$]", conn);
                da.Fill(dt);
                ConnectTestBll bll = new ConnectTestBll();
                CommonOutPutVm result = bll.ImportExcel(dt);
                if (!result.IsSuccess)
                {
                    throw new Exception(result.Message);
                }
            }
            catch (Exception ex)
            {
                f = false;
                msg = ex.Message;
            }
            return Json(new { IsSuccess = f, Message = msg }, "text/json", JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 导出EXCEL
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportTable(string UserName, int enable)
        {
            ConnectTestBll bll = new ConnectTestBll();
            List<Demo_User> list = bll.ExportTable(UserName, enable);
            var lstData = from item in list
                          select new
                          {
                              ID = item.Id,
                              用户名称 = item.UserName,
                              密码 = item.Password,
                              昵称 = item.NickName,
                              状态 = item.Status == 0 ? "不可用" : "可用",
                              创建日期 = item.CreationTime.ToString(),
                              更新日期 = item.LastUpdateTime == null ? "" : item.LastUpdateTime.ToString()
                          };


            ExportExcelResult result = new ExportExcelResult(lstData, "用户列表");
            return result;
        }
        /// <summary>
        ///  模板下载
        /// </summary>
        /// <returns></returns>
        public FileResult DownloadFile()
        {
            string filename = "导入用户信息模板";
            string fileurl = "~/ExcelTemplates/导入用户信息模板.xlsx";

            string contentType = MimeMapping.GetMimeMapping(filename);
            var extension = new FileInfo(fileurl).Extension;
            return File(fileurl, contentType, filename + extension);
        }
        #endregion
	}
}